package org.xiji.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * 主题实现类
 */
public class SubjectImpl implements Subject {
    //定义状态
    private String state;


    public SubjectImpl(String state) {
        this.state = state;
    }

    public SubjectImpl() {
    }

    public String getState() {
        return this.state;
    }

    /**
     *
     *  状态改变时调用notifyObserver方法通知所有观察者
     */
    public void setState(String state) {
        this.state = state;
        //通知所有人
        this.notifyObserver();
    }

    //注册集合
    private  List<ObserverImpl> registerList = new ArrayList<>();

    @Override
    public void register(ObserverImpl observer) {
        System.out.println(observer.getName()+"注册成功");
        registerList.add(observer);

    }

    @Override
    public void remove(ObserverImpl observer) {
        //移除元素
        registerList.remove(observer);

    }


    @Override
    public void notifyObserver() {

        //使用for循环通知遍历
        for (ObserverImpl observer : registerList) {
            observer.update(this);
        }

    }
}
